using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using D2D2.Core;
using D2D2.Core.SpriteManager;
using D2D2.Networking;
using D2D2.SharedInterfaces.Networking;
using Lidgren.Network;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace D2D2
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class MainGame : Microsoft.Xna.Framework.Game
    {
        private GraphicsDeviceManager _graphics;
        private SpriteBatch _spriteBatch;
        private PlayerManagerClient _player;

        private MouseState _oldMouseState;
        private MouseState _currentMouseState;

        private const float MIN_TIME_SINCE_LAST_INPUT = 0.05f;
        private float _timeSinceLastInput = 0.0f;
        private Texture2D _backSprite;
        private BattlefieldClient _battlefield;
        private SpriteFont _courierNew14;
        private SpriteFont _courierNew12;
        private ClientManager _clientManager = new ClientManager();
        private Rectangle _workRectangle;
        private bool _connected;

        public MainGame()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            _clientManager.Start();
            IsMouseVisible = true;

            _graphics.PreferredBackBufferWidth = 1024;
            _graphics.PreferredBackBufferHeight = 768;
            _graphics.ApplyChanges();

            _workRectangle = new Rectangle(0, 0, _graphics.PreferredBackBufferWidth, _graphics.PreferredBackBufferHeight);
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            Texture2D liveSprite = Content.Load<Texture2D>(@"Textures\Live");
            Texture2D spriteSheet = Content.Load<Texture2D>(@"Textures\Monsters");
            Texture2D chestSprite = Content.Load<Texture2D>(@"Textures\Chests");
            Texture2D dropTextrure = Content.Load<Texture2D>(@"Textures\Dollar");
            Texture2D fightTexture = Content.Load<Texture2D>(@"Textures\Fight");

            //Content.
            _courierNew14 = Content.Load<SpriteFont>(@"Fonts\Courier New 14");
            _courierNew12 = Content.Load<SpriteFont>(@"Fonts\Courier New 12");

            _backSprite = Content.Load<Texture2D>(@"Textures\greybox");

            BattleSprite.LoadTextures(spriteSheet, chestSprite, liveSprite, dropTextrure, fightTexture);
            

            ProgressManagerFactory factory = new ProgressManagerFactory(liveSprite);

            _battlefield = new BattlefieldClient(_clientManager);
            Thread.Sleep(300);
            _battlefield.Generate();

            _player = new PlayerManagerClient(factory, _courierNew14);
            Global.PlayerManager = _player;

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            ProcessNetworkMessage();

            if (!_connected) return;

            if (!Global.PlayerManager.Player.Alive) return;

            _battlefield.Update(gameTime);

            HandleMouseInput(gameTime);
            
            _player.Update(gameTime);
            base.Update(gameTime);
        }

        private void ProcessNetworkMessage()
        {
            NetIncomingMessage message;
            while ((message = _clientManager.NetClient.ReadMessage()) != null)
            {
                switch (message.MessageType)
                {
                    case NetIncomingMessageType.StatusChanged:
                        switch ((NetConnectionStatus) message.ReadByte())
                        {
                            case NetConnectionStatus.Connected:
                                NetIncomingMessage hailMessage = message.SenderConnection.RemoteHailMessage;
                                PlayerObject playerObject = new PlayerObject(hailMessage, message.SenderConnection);
                                Global.PlayerManager.Player = playerObject;
                                Global.PlayerManager.Init();
                                _connected = true;
                                break;
                        }
                        break;
                    case NetIncomingMessageType.Data:
                        HandleIncomingData(message);

                        break;
                }
            }
        }

        private void HandleIncomingData(NetIncomingMessage message)
        {
            GameMessageType gameMessageType = (GameMessageType) message.ReadByte();

            switch (gameMessageType)
            {
                case GameMessageType.MonsterState:
                    _battlefield.UpdateMonster(message);
                    break;
                case GameMessageType.ChestState:
                    _battlefield.UpdateChest(message);
                    break;
                case GameMessageType.PlayerState:
                    PlayerObject player = new PlayerObject(message);
                    Global.PlayerManager.AddSnapshot(player);
                    break;
                case GameMessageType.DropState:
                    _battlefield.UpdateDrop(message);
                    break;
                case GameMessageType.TestMessage:
                    TestMessage testMessage = new TestMessage(message);

                    Console.WriteLine(string.Format("Receive: {0}. Now: {1}", testMessage.MessageTime, NetTime.Now));

                    TestMessage responseMessage = new TestMessage();
                    _clientManager.SendMessage(responseMessage);
                    break;
            }
        }

        private void HandleMouseInput(GameTime gameTime)
        {
            _oldMouseState = _currentMouseState;

            _timeSinceLastInput += (float) gameTime.ElapsedGameTime.TotalSeconds;

            if (_timeSinceLastInput >= MIN_TIME_SINCE_LAST_INPUT)
            {
                _currentMouseState = Mouse.GetState();
                bool leftPressed = _currentMouseState.LeftButton == ButtonState.Pressed;
                //bool rightPressed = _currentMouseState.RightButton == ButtonState.Pressed;

                if ((_workRectangle).Contains(_currentMouseState.X, _currentMouseState.Y))
                {
                    if (leftPressed && _oldMouseState.LeftButton == ButtonState.Released)
                    {
                        _battlefield.MouseClickHandle(_currentMouseState.X, _currentMouseState.Y);
                    }

                    _timeSinceLastInput = 0.0f;
                }
            }
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Gray);

            if (!_connected) return;

            _spriteBatch.Begin();

            if (Global.PlayerManager.Player.Alive)
            {
                DrawBackground(_spriteBatch);

                _battlefield.Draw(_spriteBatch);

                _player.Draw(_spriteBatch);
            }
            else
            {
                _spriteBatch.DrawString(_courierNew14, "GAME OVER", new Vector2(100, 100), Color.Red);
            }
            _spriteBatch.End();

            
            base.Draw(gameTime);
        }

        private void DrawBackground(SpriteBatch spriteBatch)
        {
            int resolutionWidth = _graphics.GraphicsDevice.Viewport.Width;
            int resolutionHeight = _graphics.GraphicsDevice.Viewport.Height;

            for (int x = 0; x <= resolutionWidth / _backSprite.Width; x++)
                for (int y = 0; y <= resolutionHeight / _backSprite.Height; y++)
                {
                    Vector2 position = new Vector2(x*_backSprite.Width, y*_backSprite.Height + 80);
                    spriteBatch.Draw(_backSprite, position, Color.White);
                }
        }


    }
}
